package com.ljx.recruitment.datapatch.strategy;

import com.ljx.recruitment.common.datapatch.DataPatchPriority;
import com.ljx.recruitment.common.datapatch.DataPatchStrategy;
import com.ljx.recruitment.interview.service.ResumeService;
import com.ljx.recruitment.user.domain.entity.Role;
import com.ljx.recruitment.user.domain.entity.Tenant;
import com.ljx.recruitment.user.domain.vo.req.TenantSubmitReq;
import com.ljx.recruitment.user.domain.vo.resp.TenantResp;
import com.ljx.recruitment.user.enums.CommonRoleEnum;
import com.ljx.recruitment.user.enums.ImageKeyEnum;
import com.ljx.recruitment.user.enums.ThemeEnum;
import com.ljx.recruitment.user.event.TenantSubmitEvent;
import com.ljx.recruitment.user.service.MenuService;
import com.ljx.recruitment.user.service.RoleService;
import com.ljx.recruitment.user.service.TenantService;
import com.ljx.recruitment.user.service.UserService;
import com.ljx.recruitment.user.typehandler.details.ResumeDetails;
import com.ljx.recruitment.user.typehandler.details.ThemeDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class InitPlatformTenantDataPatch implements DataPatchStrategy {

    @Autowired
    private TenantService tenantService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public String getName() {
        return "Init-Platform-Tenant-DataPatch";
    }

    @Override
    public String getVersion() {
        return "20250225-v1";
    }

    @Override
    public Integer getSort() {
        return DataPatchPriority.HIGH;
    }

    @Override
    public void run() {
        saveTenantIfNotExist(CommonRoleEnum.PLATFORM.getKey(), CommonRoleEnum.PLATFORM.getKey());
    }

    private void saveTenantIfNotExist(String code, String name) {
        TenantResp tenantResp = tenantService.getInfoByCode(code);
        if (Objects.nonNull(tenantResp)) {
            return;
        }
        Tenant tenant = new Tenant();
        tenant.setName(name);
        tenant.setCode(code);
        initTenant(tenant);
        tenantService.save(tenant);
        applicationEventPublisher.publishEvent(new TenantSubmitEvent(this, tenant.getId()));
    }

    private void initTenant(Tenant tenant) {
        ThemeDetails themeDetails = new ThemeDetails();
        themeDetails.putAll(ImageKeyEnum.getCacheMap());
        themeDetails.putAll(ThemeEnum.getCacheMap());
        themeDetails.put(ThemeEnum.MENUS.getKey(), menuService.init());
        tenant.setThemeDetails(themeDetails);
        tenant.setResumeDetails(new ResumeDetails(resumeService.init()));
    }


}
